﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace OnlineMusic
{
    public class Data
    {
        private XmlDocument doc = new XmlDocument();
        private XmlElement root = null;
        private string path = System.Windows.Forms.Application.StartupPath + "\\Data.xml";
        public Data()
        {
            if (File.Exists(path))
            {
                doc.Load(path);
                root = doc["root"];
            }
            else
            {
                init();
            }
        }

        public bool isReady()
        {
            return root != null;
        }

        public void init()
        {
            doc.LoadXml(global::OnlineMusic.Properties.Resources.Data);
            doc.Save(path);
            root = doc["root"];
        }

        public string getLasturl()
        {
            if (!isReady())
                init();
            return root["last"]["url"].InnerText;
        }

        public void setLasturl(String url)
        {
            if (!isReady())
                init();
            root["last"]["url"].InnerText = url;
            doc.Save(path);
        }

        public XmlNodeList getFavoriteList()
        {
            if (!isReady())
                init();
            return root["favorite"].ChildNodes;
        }

        public string getFavoriteUrl(string title)
        {
            foreach (XmlElement xmlelement in getFavoriteList())
            {
                if (title == xmlelement["title"].InnerText)
                {
                    return xmlelement["url"].InnerText;
                }
            }
            return "";
        }

        public void deleteFavorite(string title)
        {
            XmlNode favorite = root["favorite"];
            foreach (XmlElement xmlelement in getFavoriteList())
            {
                if (title == xmlelement["title"].InnerText)
                {
                    favorite.RemoveChild(xmlelement);
                    doc.Save(path);
                    return;
                }
            }
        }

        public void addFavorite(string titlestr, string urlstr)
        {
            XmlElement item = doc.CreateElement("item");
            XmlElement title = doc.CreateElement("title");
            title.InnerText = titlestr;
            item.AppendChild(title);
            XmlElement url = doc.CreateElement("url");
            url.InnerText = urlstr;
            item.AppendChild(url);
            root["favorite"].AppendChild(item);
            doc.Save(path);
        }
    }
}
